package com.wzy.controller;

import com.wzy.pojo.SysUser;
import com.wzy.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @auth wzy
 * @date 2023/11/7 15:02
 */
@Controller
public class LoginController {

    @Autowired
    private SysUserService sysUserService;

    @PostMapping("/login")
    public String login(Model model, HttpServletRequest request
            , String account, String password){
        // 调用业务层， 验证用户名和密码
        SysUser sysUser = sysUserService.login(account, password);

        if (sysUser == null){
            model.addAttribute("errorMsg","用户名或密码错误");
            return "login";
        }

        request.getSession().setAttribute("userSession",sysUser);

        return "redirect:frame";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "login";
    }

    @GetMapping("/frame")
    public String frame(){

        return "frame";
    }

    @ExceptionHandler(RuntimeException.class)
    public String error(Model model, RuntimeException e){
        model.addAttribute("e",e);
        return "sysError";
    }
}
